<template>
  <div class="user-profile-container" v-loading="loading">
    <el-card v-if="userProfile">
      <template #header>
        <h2>用户资料 - {{ userProfile.username }}</h2>
      </template>
      
      <div class="profile-avatar">
        <el-upload
          class="avatar-uploader"
          action="/users/avatar"
          :show-file-list="false"
          :headers="uploadHeaders"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="userProfile.avatar" :src="userProfile.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户名">{{ userProfile.username }}</el-descriptions-item>
        <el-descriptions-item label="全名">
          <span v-if="!editMode">{{ userProfile.fullName || '未设置' }}</span>
          <el-input v-else v-model="editableProfile.fullName" size="small"></el-input>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userProfile.email }}</el-descriptions-item> 
        <el-descriptions-item label="头像预览" v-if="userProfile.avatar && !editMode">
          <el-avatar :size="100" :src="userProfile.avatar" @error="() => true">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </el-descriptions-item>
         <el-descriptions-item label="头像预览" v-if="editableProfile.avatar && editMode">
          <el-avatar :size="100" :src="editableProfile.avatar" @error="() => true">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </el-descriptions-item>
      </el-descriptions>

      <div class="actions mt-4">
        <el-button type="primary" @click="toggleEditMode" v-if="!editMode">编辑资料</el-button>
        <template v-if="editMode">
          <el-button type="success" @click="saveProfile" :loading="saving">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </template>
      </div>
    </el-card>
    <el-empty description="无法加载用户资料" v-else-if="!loading && !userProfile"></el-empty>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 图片压缩函数
const compressImage = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        
        // 计算压缩后的尺寸
        let width = img.width
        let height = img.height
        const maxSize = 800 // 最大尺寸
        
        if (width > height && width > maxSize) {
          height = Math.round((height * maxSize) / width)
          width = maxSize
        } else if (height > maxSize) {
          width = Math.round((width * maxSize) / height)
          height = maxSize
        }
        
        canvas.width = width
        canvas.height = height
        
        // 绘制图片
        ctx.drawImage(img, 0, 0, width, height)
        
        // 转换为Blob
        canvas.toBlob((blob) => {
          resolve(new File([blob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          }))
        }, 'image/jpeg', 0.8) // 压缩质量为0.8
      }
    }
  })
}

export default {
  name: 'UserProfile',
  setup() {
    const userProfile = ref(null);
    const loading = ref(true);
    const editMode = ref(false);
    const saving = ref(false);
    const editableProfile = reactive({
      fullName: '',
      avatar: ''
    });

    const uploadHeaders = computed(() => ({
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }));

    const fetchUserProfile = async () => {
      loading.value = true;
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/users/me', {
          headers: { Authorization: `Bearer ${token}` }
        });
        userProfile.value = response.data; 
        editableProfile.fullName = response.data.fullName || '';
        editableProfile.avatar = response.data.avatar || '';
      } catch (error) {
        ElMessage.error('获取用户资料失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };

    const toggleEditMode = () => {
      editMode.value = !editMode.value;
      if (editMode.value && userProfile.value) {
        // Reset editable fields from current profile if re-entering edit mode
        editableProfile.fullName = userProfile.value.fullName || '';
        editableProfile.avatar = userProfile.value.avatar || '';
      }
    };

    const saveProfile = async () => {
      saving.value = true;
      try {
        const token = localStorage.getItem('token');
        const response = await axios.put('/users/me', editableProfile, {
          headers: { Authorization: `Bearer ${token}` }
        });
        userProfile.value = response.data; // Update profile with response
        // Update local storage user info if necessary
        const localUser = JSON.parse(localStorage.getItem('user') || '{}');
        localUser.fullName = response.data.fullName;
        localUser.avatar = response.data.avatar;
        localStorage.setItem('user', JSON.stringify(localUser));

        ElMessage.success('用户资料更新成功');
        editMode.value = false;
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '更新用户资料失败');
        console.error(error);
      } finally {
        saving.value = false;
      }
    };

    const cancelEdit = () => {
      editMode.value = false;
      // Optionally reset editableProfile to original values if needed
      if(userProfile.value){
        editableProfile.fullName = userProfile.value.fullName || '';
        editableProfile.avatar = userProfile.value.avatar || '';
      }
    };

    const handleAvatarSuccess = (response) => {
      userProfile.value.avatar = response.url
      ElMessage.success('头像上传成功')
      // 更新localStorage
      const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
      userInfo.avatar = response.url
      localStorage.setItem('user', JSON.stringify(userInfo))
    }

    const beforeAvatarUpload = async (file) => {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
      }

      try {
        // 压缩图片
        const compressedFile = await compressImage(file)
        // 替换原始文件
        Object.defineProperty(compressedFile, 'name', {
          value: file.name
        })
        return compressedFile
      } catch (error) {
        console.error('图片压缩失败:', error)
        ElMessage.error('图片处理失败')
        return false
      }
    }

    onMounted(() => {
      fetchUserProfile();
    });

    return {
      userProfile,
      loading,
      editMode,
      editableProfile,
      saving,
      toggleEditMode,
      saveProfile,
      cancelEdit,
      handleAvatarSuccess,
      beforeAvatarUpload,
      uploadHeaders
    };
  }
};
</script>

<style scoped>
.user-profile-container {
  padding: 20px;
  max-width: 700px;
  margin: auto;
}
.mt-4 {
  margin-top: 20px;
}
.actions {
  text-align: right;
}
.profile-avatar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}
</style> 